<template>
    <div>
      <vab-card>
        <template #header>
          <span class="leve_title">寄售查询</span>
        </template>
        <template #default>
          <el-form
            :ref="(el) => (searchFormRef = el)"
            :model="searchForm"
            label-width="130px"
            class="form_search composite_form"
          >
            <el-row :gutter="24">
              <el-col v-for="(item, i) in CheckSearch"
                :key="i" :xs="24" :sm="12" :md="12" :lg="8" :xl="8"
                v-show="(!isMore && i < 1) || isMore"
              >
                <!-- 默认项 -->
                <el-form-item
                  v-if="item.type == 'select'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <VabSelectForm
                    v-if="selectOptions(item.prop)"
                    v-model.trim="searchForm[item.prop]"
                    :multiple="item.multiple"
                    :options="selectOptions(item.prop)"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
                <!-- autocomplete -->
                <el-form-item
                  v-if="item.type == 'autocomplete'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <VabAutoFrom v-model.trim="searchForm[item.prop]" :list="selectOptions(item.prop)"/>
                </el-form-item>
                <!-- input -->
                <el-form-item
                  v-if="item.type == 'input'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <el-input
                    clearable
                    placeholder="请输入"
                    class="width_100 height_auto"
                    v-model.trim="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
                <!-- time -->
                <el-form-item
                  v-if="item.type == 'time'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <el-date-picker
                    clearable
                    placeholder="请选择"
                    type="datetimerange"
                    class="width_100 height_auto"
                    :format="TimeFormat"
                    :default-time="DefaultTime"
                    v-model="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
                <!-- 一级类目 -->
                <el-form-item
                  v-if="item.type == 'select_1'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <el-select
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                    class="width_100 height_auto"
                    :multiple="item.multiple"
                    :filterable="item.multiple"
                    v-model.trim="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                    @change="(value: string) => {
                      _ProductSearchClass(value)
                    }"
                  >
                    <el-option
                      clearable
                      v-for="(jtem, j) in selectOptions(item.prop)"
                      :key="jtem.value"
                      :label="jtem.label"
                      :value="jtem.value"
                    />
                  </el-select>
                </el-form-item>
                <!-- 二级类目 -->
                <el-form-item
                  v-if="item.type == 'select_2'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <el-select
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                    class="width_100 height_auto"
                    :multiple="item.multiple"
                    :filterable="item.multiple"
                    v-model.trim="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                  >
                    <el-option
                      clearable
                      v-for="(jtem, j) in classTwoList"
                      :key="jtem.value"
                      :label="jtem.label"
                      :value="jtem.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 复合查询 -->
              <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" >
                <div class="flex">
                  <span class="composite">
                    <el-select
                      class="composite_label"
                      v-model="compositeValue"
                      @change="handleComposite"
                    >
                      <el-option
                        v-for="item in ConsignSaleCheckCompositeSearch"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </span>
                  <VabRangeForm :ref="(el) => vabRangeFormRef = el"/>
                </div>
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" >
                <div class="flex_just_end">
                  <el-button size="small" type="primary" @click="handleSearch()">
                    查询
                  </el-button>
                  <el-button size="small" @click="resetForm(searchFormRef)">
                    重置
                  </el-button>
                  <div class="sqFontSize" @click="isMore = !isMore">
                    更多
                    <el-icon v-if="isMore"><ArrowUp /></el-icon>
                    <el-icon v-else><ArrowDown /></el-icon>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vab-card>
      <!-- 主 -->
      <vab-card shadow="always">
        <template #header>
          <span class="leve2_title">寄售列表</span>
        </template>
        <!-- 总计块 -->
        <div class="flex" v-if="data.summary">
          <div class="box_count">
            总库存： <span>{{ NumberFormat(data.summary?.quantity) || 0 }}</span>
          </div>
        </div>
        <el-table
          border
          height="500"
          style="width: 100%"
          :data="data.dataSource"
          v-loading="data.loading"
        >
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">
              <span
                class="ellipsis"
                v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, i) in data.cloums"
            :key="i"
            :width="item.width"
            :prop="item.prop"
            :label="item.label"
            :align="item.type == 'money' || item.type == 'number' ? 'right' : 'center'"
          >
            <template #header>
              {{ item.label }}
              <!-- <VabFifterTable v-if="item.prop" :keyword="item.prop"/> -->
            </template>

            <template #default="scope">
              <!-- 自定义 -->
              <div v-if="item.type == 'custom'">
                <span class="ellipsis link text_right" @click="() => { orderDialogRef.open(scope.row) }">
                  {{ _FieldFormat(scope.row[item.prop], 'number') }}
                </span>
              </div>
              <!-- 正常 -->
              <div
                v-else
                class="ellipsis"
              >
                {{ _FieldFormat(scope.row[item.prop], item.type) }}
              </div>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="主仓库存明细账" align="center" width="130" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleLink(scope.row)">主仓明细账</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex_just_end">
          <el-pagination
            background
            small="small"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            layout="total, prev, pager, next,sizes, jumper"
            :page-sizes="[20, 50, 100, 200]"
            :pager-count="10"
            :total="data.count"
            @current-change="handlePageNum"
            @size-change="handlePageSize"
          />
        </div>
      </vab-card>
      <!-- 订单弹窗 -->
      <OrderDialog ref="orderDialogRef"/>
    </div>
  </template>
  <!-- 寄售查询 -->
<script lang="ts" setup>
defineOptions({
  name: 'ConsignSaleCheck',
})
/**
 * @import
 */
import {
  CheckSearch,
  OtherOutSearchSelect,
  ConsignSaleCheckCloums,
  ConsignSaleCheckCompositeSearch
} from './components/tools'
import { FieldFormat, TimeFormat, DefaultTime, NumberFormat } from '~/src/utils/utils'
import { ElMessage, FormInstance, dayjs } from 'element-plus'
import { getStockConsignBatch, getInventorySearch, getInventoryStock, getInventoryStockIn } from '~/src/api/dms/inventory';
import { productSearchClass } from '~/src/api/dms/product';
import OrderDialog from './components/OrderDialog.vue'

/**
 * @var
 */
const router = useRouter()
const searchFormRef = ref<any>(null)
const vabRangeFormRef = ref<any>(null)
const orderDialogRef = ref()
const searchForm = reactive<any>({})
const data = reactive<any>({
  dataSource: [],
  cloums: [],
  pageNum: 1,
  pageSize: 20,
  count: 0,
  search: {},
  summary: null
})
data.dataSource = []
data.cloums = ConsignSaleCheckCloums

// 复合体
const compositeValue = ref('quantity')
let isCheck = ref(false)
let classTwoList = ref<any>([])
// 订单占有弹窗
let orderVisible = ref(false)
const isMore = ref(false)
/**
 * @method
 */
const handleSearch = async (value = '') => {
  isCheck.value = true
  await _GetProductList()
  ElMessage({
    message: '查询成功',
    type: 'success',
  })
}
// 重置
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  isCheck.value = false
  await formEl.resetFields()
  await _GetProductList()
  if (vabRangeFormRef.value) vabRangeFormRef.value.reset()
  compositeValue.value = 'quantity'
  ElMessage({
    message: '重置成功',
    type: 'success',
  })
}
// 回车
const onkeydown = (value: any) => {
  isCheck.value = true
  _GetProductList()
}
// 复合筛选
const handleComposite = (value: any) => {
  vabRangeFormRef.value.reset()
}
const handleLink = (row: any) => {
  router.push({
    path: '/inventory/warehouse',
    query: {
      stock_id: row.id,
      from: 'consignSaleCheck'
    },
  })
}
// 页码
const handlePageNum = (value: any) => {
  data.pageNum = value
  _GetProductList()
}
// 页数
const handlePageSize = (value: any) => {
  data.pageSize = value
  _GetProductList()
}

// 筛选项格式化
const selectOptions = (value: string) => {
  if (JSON.stringify(data.search) == '{}') return
  return OtherOutSearchSelect(data.search, value)
}
// 字段级格式化
const _FieldFormat = (value: string, type = '') => {
  return FieldFormat(value, type)
}
// 获取数据
const _GetProductList = async () => {
  data.loading = true

  // 解构区间
  let vStart = vabRangeFormRef.value.vStart
  let vEnd = vabRangeFormRef.value.vEnd

  let _searchForm = { ...searchForm }
  if (!isCheck.value) {
    _searchForm = {}
    vStart = ''
    vEnd = ''
  }

  // 复合项
  const composite = compositeValue.value

  const query = {
    page: data.pageNum,
    limit: data.pageSize,
    filter: {
      assistant_id: _searchForm.assistant_id || '', // 品牌
      class_id1: searchForm.class_id1 || '', // 一级类目
      class_id2: searchForm.class_id2 || '', // 二级类目
      xl_id: _searchForm.xl_id || '', // 系列
      barcode: _searchForm.barcode || '', // 条码
      number: _searchForm.number || '', // 产品编码
      name: _searchForm.name || '', // 产品名称
      quantity_start: composite == 'quantity' ? vStart : '', // 总库存开始
      quantity_end: composite == 'quantity' ? vEnd : '', // 总库存结束
      order_own_num_start: composite == 'order_own_num' ? vStart : '', // 订单占有开始
      order_own_num_end: composite == 'order_own_num' ? vEnd : '', // 订单占有结束
      available_num_start: composite == 'available_num' ? vStart : '', // 可用库存期开始
      available_num_end: composite == 'available_num' ? vEnd : '', // 可用库存结束
    },
  }
  try {
    const res = await getStockConsignBatch({ ...query })

    const { list, count, summary } = res.data

    data.dataSource = list
    data.count = count
    data.summary = summary

    data.loading = false
  } catch (error) { }
}
// 其他出入库筛选项
const _GetProductSearch = async () => {
  try {
    const res = await getInventorySearch()
    await res.data.brand.push({ entry_id: '', name: '空' })
    await res.data.series.push({ id: '', data_title: '空' })
    data.search = await res.data
    classTwoList.value = selectOptions('class_id2')
  } catch (error) { }
}
// // 二级分类
const _ProductSearchClass = async (class_id: any) => {
  classTwoList.value = []
  try {
    const res = await productSearchClass({ class_id })
    classTwoList.value = res.data.map((item: any) => {
      return {
        value: item.id,
        label: item.data_title
      }
    })
  } catch (error) {

  }
}

onMounted(() => {
  _GetProductList()
  _GetProductSearch()
})
</script>

<style lang="scss" scoped>
@import '../../components/public.scss';
</style>
